#!/usr/local/bin/python
# -*- coding: utf-8 -*-

#import qdarkstyle
import sys
import traceback
from PyQt5.QtCore import Qt



from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox, QDialog

import init
from AccountBookWidget import AccountBookWidget
from AccountVoucherWidget import AccountVoucherWidget
from AlipayBillWidget import AlipayBillWidget
from BalanceSheetWidget import BalanceSheetWidget
from CashFlowStatementWidget import CashFlowStatementWidget
from IncomeStatementWidget import IncomeStatementWidget
from LoginDialog import LoginDialog
from RuleEditorDialog import RuleEditorDialog
from StatisticalChartWidget import StatisticalChartWidget
from XirrWorkWidget import XirrWorkWidget

from ui.MainWindowsUI import Ui_MainWindow
from initLogger import logger

class MainForm(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainForm, self).__init__()
        self.setupUi(self)

        self.showLoginDialog()

        #设置图标
        self.setWindowIcon(QIcon("./img/icon_a.ico"))



        self.accountVoucherWidget = AccountVoucherWidget()
        self.accountBookWidget = AccountBookWidget()
        self.balanceSheetWidget = BalanceSheetWidget()
        self.incomeStatementWidget = IncomeStatementWidget()
        self.cashFlowStatementWidget = CashFlowStatementWidget() #AccountBookWidget()  #页面开启后再重新定义,未实现
        self.alipayBillWidget = AlipayBillWidget()   #支付宝账单页面
        self.statisticalChartWidget =StatisticalChartWidget()  #统计图表页面
        self.xirrWorkWidget = XirrWorkWidget()


        self.widgetPageList = [self.accountVoucherWidget,
                               self.accountBookWidget,
                               self.balanceSheetWidget,
                               self.incomeStatementWidget,
                               self.cashFlowStatementWidget,
                               self.alipayBillWidget,
                               self.statisticalChartWidget,
                               self.xirrWorkWidget
                               ]


        

        self.showAccountVoucher()

        # 点击actionList,子窗口就会显示在主窗口的MaingridLayout中
        self.accountVoucherAction.triggered.connect(self.showAccountVoucher)
        self.accountBookAction.triggered.connect(self.showAccountBook)
        self.balanceSheetAction.triggered.connect(self.showBalanceSheet)
        self.incomeStatementAction.triggered.connect(self.showIncomeStatement)
        self.cashFlowStatementAction.triggered.connect(self.showCashFlowStatement)  #暂未实现


        self.yearCarryOverAction.triggered.connect(self.doYearCarryOver)  #暂未实现
        self.alipayBillAction.triggered.connect(self.showAlipayBill)
        self.modifySubjectAction.triggered.connect(self.showModifySubject)
        self.statisticalChartAction.triggered.connect(self.showStatisticalChart)
        self.xirrWorkAction.triggered.connect(self.showXirrWorkStatement)
        self.ruleEditorAction.triggered.connect(self.showRuleEditorDialog)


    def showLoginDialog(self):
        '''
        函数功能：展示登录对话框
        :return:
        '''

        loginDialog = LoginDialog(parent=self)
        # ruleEditorDialog.setWindowModality(Qt.NonModal)
        loginDialog.setWindowModality(Qt.WindowModal)

        result = loginDialog.exec_()
        if result == QDialog.Accepted:
            logger.debug("登录成功，进入主应用程序...")
            pass
        else:
            logger.debug("用户取消登录")
            sys.exit(0)
        #loginDialog.destroy()

    def showWidgetPage(self, widgetPageName):
        '''
        函数功能：对指定页面进行显示
        :param pageName:
        :return:
        '''

        for i in range(len(self.widgetPageList)):
            if widgetPageName == i:
                self.widgetPageList[i].show()
            else:
                self.widgetPageList[i].hide()


    def showAccountVoucher(self):
        '''
        函数功能：展示记账凭证页面
        :return:
        '''

        #self.children_window_horizontalLayout.addWidget(self.accountVoucherWidget)

        self.mainGridLayout.addWidget(self.accountVoucherWidget)
        self.showWidgetPage(init.ACCOUNT_VOUCHER_PAGE)



    def showAccountBook(self):
        '''
        函数功能：展示账簿页面
        :return:
        '''
        self.mainGridLayout.addWidget(self.accountBookWidget)
        self.showWidgetPage(init.ACCOUNT_BOOK_PAGE)

    def showBalanceSheet(self):
        '''
        函数功能：展示资产负债表页面
        :return:
        '''
        self.mainGridLayout.addWidget(self.balanceSheetWidget)
        self.showWidgetPage(init.BALANCE_SHEET_PAGE)


    def showIncomeStatement(self):
        '''
        函数功能：展示收支表页面
        :return:
        '''
        self.mainGridLayout.addWidget(self.incomeStatementWidget)
        self.showWidgetPage(init.INCOME_STATEMENT_PAGE)

    def showCashFlowStatement(self):
        '''
        函数功能：展示现金流表页面
        :return:
        '''

        self.mainGridLayout.addWidget(self.cashFlowStatementWidget)
        self.showWidgetPage(init.CASH_FLOW_STATEMENT_PAGE)


    def showModifySubject(self):
        '''
        函数功能：显示记账科目修改对话框
        :return:
        '''
        pass

        QMessageBox.information(None,
                            '消息',
                            '功能还未实现',
                            QMessageBox.Yes)

    def showStatisticalChart(self):
        '''
        函数功能：展示统计图表页面
        :return:
        '''

        self.mainGridLayout.addWidget(self.statisticalChartWidget)
        self.showWidgetPage(init.STATISTICAL_CHART_PAGE)

    def showXirrWorkStatement(self):
        '''
        函数功能：展示年度收益率页面
        :return:
        '''
        self.mainGridLayout.addWidget(self.xirrWorkWidget)
        self.showWidgetPage(init.XIRR_WORK_PAGE)

    def doYearCarryOver(self):
        '''
        函数功能：完成年度结转工作
        该功能已在“initFirstMonthForYearAccountBook”函数中实现
        :return:
        '''
        #暂时未实现
        pass
        QMessageBox.information(None,
                            '消息',
                            '该功能已在“initFirstMonthForYearAccountBook”实现自动触发，无需人工操作',
                            QMessageBox.Ok)

        #QMessageBox.information(None, "【错误】添加失败", message, QMessageBox.Ok)
    def showAlipayBill(self):
        '''
        函数功能：展示支付宝账单页面
        :return:
        '''
        self.mainGridLayout.addWidget(self.alipayBillWidget)
        self.showWidgetPage(init.ALIPAY_BILL_PAGE)


    def showRuleEditorDialog(self):
        ruleEditorDialog = RuleEditorDialog(parent=self)
        #ruleEditorDialog.setWindowModality(Qt.NonModal)
        ruleEditorDialog.setWindowModality(Qt.WindowModal )


        if ruleEditorDialog.exec_():
            pass
        ruleEditorDialog.destroy()


    def showRuleEditorDialog_modal(self):
        pass





if __name__ == "__main__":

    try:
        # PyQt5高清屏幕自适应设置,以及让添加的高清图标显示清晰，不然designer导入的图标在程序加载时会特别模糊
        #QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        #QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)

        app = QApplication(sys.argv)
        win = MainForm()
        win.show()
        #app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
        #app.setStyleSheet(qdarkgraystyle.load_stylesheet_pyqt5())

        sys.exit(app.exec_())


    except Exception as e:
        s = traceback.format_exc()

        # 使用 logging + traceback 模块输出异常
        #logger.info(u"使用 traceback 输出异常: {}".format(s))

        # 使用 logging 自定义参数输出异常
        #logger.error(u"使用 logging error 参数 exc_info=True 输出异常", exc_info=True)

        # 也可以直接使用 logging 的 exception 函数输出异常堆栈信息
        logger.exception(u"使用logging exception 函数直接输出异常堆栈 {}".format(e))

        # logging.exception(e)

        print("Error: ", e)